package com.talent.jiwen.receiver;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.abc.live.ABCLiveUIHelp;
import com.abcpen.core.define.ABCConstants;
import com.abcpen.open.api.model.RoomMo;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.talent.jiwen.ActivityManager;
import com.talent.jiwen.IndexActivity;
import com.talent.jiwen.R;
import com.talent.jiwen.chatlive.InteractiveActivity;
import com.talent.jiwen.data.JPushCommonInfo;
import com.talent.jiwen.data.JPushExtraData;
import com.talent.jiwen.home.InviteDetailActivity;
import com.talent.jiwen.home.TogetherListActivity;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.teacher.CourseAllListFragment;
import com.talent.jiwen.teacher.CourseFragment;
import com.talent.jiwen.teacher.CourseListFragment;
import com.talent.jiwen.teacher.CourseWaitListFragment;
import com.talent.jiwen.ui.widgets.RemindDialog;
import com.talent.jiwen.util.LogUtil;
import com.talent.jiwen.util.MaterialDialogUtil;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import cn.robotpen.utils.screen.LogUtils;
import rx.Observable;

public class MyJPushReceiver extends BroadcastReceiver {
    private static String TAG = "MyJPushReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        //Log.d(TAG, "onReceive - " + intent.getAction());

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {

        }
        // 自定义消息不会展示在通知栏，完全要开发者写代码去处理
        else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent
                .getAction())) {
            String content = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);

            LogUtils.e("收到了自定义消息@@消息内容是:" + content);
            LogUtils.e("收到了自定义消息@@消息extra是:" + extra);

            try {
                Gson gson = new Gson();
                JPushExtraData extraData = JSON.parseObject(extra , JPushExtraData.class);
                String extraMessage  = extraData.getExtraMessage();

                JPushCommonInfo message = gson.fromJson(extraMessage, JPushCommonInfo.class);
                int messageType = message.getMessageType();

                switch (messageType){
                    case JPushCommonInfo.INVITE_RESULT:
                        //邀请拼班结果
                        EventBus.getDefault().post(TogetherListActivity.EVENT_REFRESH_INVITE_LIST);
                        break;
//                    case JPushCommonInfo.TEACHER_TIME_OVER://免单课程结束
//                        EventBus.getDefault().post(InteractiveActivity.TIME_FINISH_CLASS);
//                        EventBus.getDefault().post(CourseListFragment.REFRESH_COURSE_LIST);
//                        EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
//                        EventBus.getDefault().post(CourseAllListFragment.REFRESH_COURSE_ALL_LIST);
//                        break;

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        //通知消息到达
        else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent
                .getAction())) {
            String extra  =bundle.getString(JPushInterface.EXTRA_EXTRA);
            LogUtils.e("收到了通知消息@@消息extra是:" + extra);
            try {
                Gson gson = new Gson();
                JPushExtraData extraData = JSON.parseObject(extra , JPushExtraData.class);
                String extraMessage  = extraData.getExtraMessage();

                JPushCommonInfo message = gson.fromJson(extraMessage , JPushCommonInfo.class);
                int messageType = message.getMessageType();
                switch (messageType){
                    case JPushCommonInfo.INVITE_REQUEST:
                        Map<String , Object> map = message.getMessageMap();
                        Double groupId = (Double) map.get("groupId");
                        Double orderId = (Double) map.get("orderId");

                        showInviteDialog(orderId.intValue() + "" , groupId.intValue() + "");

                        break;
                    case JPushCommonInfo.START_COURSE:
                        //开始上课
                        Map<String , Object> startCourseMap = message.getMessageMap();
                        Double roomId = (Double) startCourseMap.get("roomId");
                        showStartClassDialog(roomId.intValue() + "");

                        EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                        break;
                    case JPushCommonInfo.TEACHER_GET_ORDER:
                        //有教师抢单
                        EventBus.getDefault().post(CourseListFragment.REFRESH_COURSE_LIST);
                        break;
                    case JPushCommonInfo.STUDENT_LATE:
                        //学生迟到
                        break;
                    case JPushCommonInfo.TEACHER_LATE:
                        //教师迟到
                        break;
                    case JPushCommonInfo.STUDENT_CANCEL:
                    case JPushCommonInfo.TEACHER_CANCEL:
                        EventBus.getDefault().post(CourseListFragment.REFRESH_COURSE_LIST);
                        EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                        EventBus.getDefault().post(CourseAllListFragment.REFRESH_COURSE_ALL_LIST);
                        break;

                }

            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        //通知消息点击
        else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent
                .getAction())) {
            String extra  =bundle.getString(JPushInterface.EXTRA_EXTRA);
            LogUtils.e("收到了通知消息@@消息extra是:" + extra);

            try {
                Gson gson = new Gson();
                JPushExtraData extraData = JSON.parseObject(extra , JPushExtraData.class);
                String extraMessage  = extraData.getExtraMessage();

                JPushCommonInfo message = gson.fromJson(extraMessage , JPushCommonInfo.class);
                int messageType = message.getMessageType();
                switch (messageType){
                    case JPushCommonInfo.INVITE_REQUEST:
                        //邀请拼班请求
                        Map<String , Object> map = message.getMessageMap();
                        Double groupId = (Double) map.get("groupId");
                        Double orderId = (Double) map.get("orderId");

                        InviteDetailActivity.startInviteDetailActivity(context , groupId.intValue() + "" , orderId.intValue() + "");

                        break;
                    case JPushCommonInfo.STUDENT_ACCEPT_ORDER:
                        //学生接受老师抢单
                        Intent courseSureIntent = new Intent(context, IndexActivity.class);
                        IndexActivity.tab2checked = true;
                        courseSureIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(courseSureIntent);
                        CourseFragment.fragment2checked = true;
                        EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                        break;
                    case JPushCommonInfo.START_COURSE:
                        //开始上课
                        Intent startSureIntent = new Intent(context, IndexActivity.class);
                        IndexActivity.tab2checked = true;
                        startSureIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(startSureIntent);
                        CourseFragment.fragment2checked = true;
                        EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                        break;
                    case JPushCommonInfo.TEACHER_GET_ORDER:
                        //有教师抢单
                        Intent teacherOrderIntent  = new Intent(context, IndexActivity.class);
                        IndexActivity.tab2checked = true;
                        teacherOrderIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(teacherOrderIntent);
                        EventBus.getDefault().post(CourseListFragment.REFRESH_COURSE_LIST);
                        break;

                    case JPushCommonInfo.STUDENT_LATE://学生上课逾期通知
                    case JPushCommonInfo.TEACHER_LATE://教师上课逾期通知
                    case JPushCommonInfo.STUDENT_CANCEL://学生取消订单，已确认
                    case JPushCommonInfo.TEACHER_CANCEL://老师取消订单

                        Intent courseIntent = new Intent(context, IndexActivity.class);
                        IndexActivity.tab2checked = true;
                        courseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(courseIntent);

                        CourseFragment.fragment2checked = true;
                        EventBus.getDefault().post(CourseListFragment.REFRESH_COURSE_LIST);
                        EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                        EventBus.getDefault().post(CourseAllListFragment.REFRESH_COURSE_ALL_LIST);
                        break;
                    default:
                        Intent defaultIntent = new Intent(context, IndexActivity.class);
                        defaultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(defaultIntent);
                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        else {
        }
    }


    /**显示邀请
     *
     * @param orderId
     * @param groupId
     */
    private void showInviteDialog(final String orderId , final String groupId){
        if (!Validators.isEmpty(SPUtil.getUserId())){
            final Activity activity = ActivityManager.getAppManager().currentActivity();
            if (null != activity){
                RemindDialog dialog = MaterialDialogUtil.getRemindDialog(activity,R.mipmap.dialog_start_course, "有朋友邀请你拼班啦"
                        , "取消", "立即进入"
                        , new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                InviteDetailActivity.startInviteDetailActivity(activity , groupId , orderId);
                            }
                        });
                dialog.show();
            }
        }



    }


    /**显示上课Dialog
     *
     * @param roomId
     */
    private void showStartClassDialog(final String roomId){
        if(!Validators.isEmpty(SPUtil.getUserId())){
            Activity activity = ActivityManager.getAppManager().currentActivity();
            if(null != activity){
                RemindDialog dialog = MaterialDialogUtil.getOneOptionRemindDialog(activity, R.mipmap.dialog_start_course , "你预约的课程已经开始啦!"
                        , "立即进入", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                joinClass(roomId);
                            }
                        });
                dialog.show();
            }

        }

    }


    /**学生失信通知
     *
     */
    private void showStudentLateDialog(){
        if(!Validators.isEmpty(SPUtil.getUserId())){
            Activity activity = ActivityManager.getAppManager().currentActivity();
            if (null != activity){
                RemindDialog dialog = MaterialDialogUtil.getRemindDialog(activity, R.mipmap.dialog_start_course , "你有几次失信行为"
                        , "取消", "查看"
                        , new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        });
                dialog.show();
            }
        }


    }

    /**教师失信通知
     *
     */
    private void showTeahcerLateDialog(){
        if(!Validators.isEmpty(SPUtil.getUserId())){
            Activity activity = ActivityManager.getAppManager().currentActivity();
            if(null != activity){
                RemindDialog dialog = MaterialDialogUtil.getRemindDialog(activity, R.mipmap.dialog_start_course , "老师未按时间上课，课程已取消"
                        , "取消", "查看"
                        , new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        });
                dialog.show();
            }
        }


    }

    /**学生加入课程
     *
     * @param roomId
     */
    private void joinClass(final String roomId){
        Activity activity = ActivityManager.getAppManager().currentActivity();
        Map<String, String> map = new HashMap<>();
        map.put("studentId", SPUtil.stringOut(SPConstant.USER_ID));
        map.put("orderId", roomId);

        Observable observable = ApiFactory.getEducationApiSingleton().studentJoinClass(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber(activity) {
            @Override
            protected void _onNext(Object o) {
                goLive(roomId);
            }

            @Override
            protected void _onError(String message) {

            }
        } , true);
    }


    /**
     * 进入房间
     *
     * @param roomId
     */
    public void goLive(String roomId) {
        String rid = roomId;
        int liveType = 2;
//        roleType = ABCConstants.USER_OTHER;//学生
        ABCLiveUIHelp uiHelp = ABCLiveUIHelp.init()
                .setUserID(SPUtil.getBSUId())
                .setUserName(SPUtil.getUserName())
                .setIsManager(false)
                .setDefaultOpenCamera(true)
                .setDefaultOpenMic(true);

        RoomMo roomMo = new RoomMo();
        roomMo.room_id = rid;
        roomMo.name = rid;
        roomMo.live_type = liveType;

        startLiveActivity(uiHelp, roomMo);
    }


    private boolean isManager = false;
//    private boolean isRecording = true;
//    private int roleType = ABCConstants.USER_OTHER;

    /**
     * Room 基本废弃掉  可以自行更改
     *
     * @param uiHelp
     * @param roomMo
     */
    public void startLiveActivity(ABCLiveUIHelp uiHelp, RoomMo roomMo) {
        ABCLiveUIHelp abcLiveUIHelp = null;
        if(!SPUtil.booleanDataOut(SPConstant.IS_FIRST_GUIDE)){
            abcLiveUIHelp= uiHelp.setIsShowGuide(true);
            SPUtil.booleanDataIn(SPConstant.IS_FIRST_GUIDE,true);
        }else{
            abcLiveUIHelp= uiHelp.setIsShowGuide(false);
        }
        abcLiveUIHelp.setIsManager(isManager);
        roomMo.isRecord = 1;
        abcLiveUIHelp.setUserIconDefault(R.drawable.abc_default_icon);
        abcLiveUIHelp.setUserAvatarUrl(SPUtil.getUserHeadImg());
//        abcLiveUIHelp.setEndTime(System.currentTimeMillis() + 45 * 1000);
        abcLiveUIHelp.setStartTime(System.currentTimeMillis() + 10 * 1000);
        abcLiveUIHelp.setRoleType(isManager ? ABCConstants.MANAGER_TYPE : ABCConstants.NONE_TYPE);
        Activity activity = ActivityManager.getAppManager().currentActivity();
        abcLiveUIHelp.startInteractiveLiveActivity(activity, roomMo, InteractiveActivity.class);
    }
}
